package com.example.demo01.controller;

import cn.hutool.core.date.DateUtil;
import com.example.demo01.i18n.InternationalizeTools;
import com.example.demo01.i18n.I18nConstant;
import com.example.demo01.i18n.ServiceCodeConstant;
import com.example.demo01.request.I18nParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * @author wangxun
 */
@Slf4j
@RestController
@RequestMapping("/i18n")
public class I18NController {

    private static final String REQUEST_SUCCESS = "请求发送成功";

    @Autowired
    private InternationalizeTools internationalizeTools;

    @GetMapping("/hellWorld")
    public String hellWorld() {
        return internationalizeTools.getI18nProperties(ServiceCodeConstant.HELLO, I18nConstant.FAIL);
    }

    @PostMapping("/helloTime")
    public String helloTime(@RequestBody I18nParam i18nParam) {
        log.info("{}", DateUtil.formatDateTime(i18nParam.getChoseTime()));
        return REQUEST_SUCCESS;
    }

    /**
     * http://localhost:8080/i18n/requestContextHolder
     *
     * @return
     */
    @GetMapping("/requestContextHolder")
    public String requestContextHolder() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        return REQUEST_SUCCESS;
    }

    @GetMapping("/localeContextHolder")
    public String localeContextHolder() {
        Locale locale = LocaleContextHolder.getLocale();
        return REQUEST_SUCCESS;
    }
}
